package com.example.converter;

import com.example.bean.IKey;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author GYL
 * @dateTime 2020/4/20-16:11
 * @description
 */
public class CustomConverterFactory extends Converter.Factory{
  
  public static CustomConverterFactory create() {
    return create(new SpecialParse());
  }
  
  public static CustomConverterFactory create(SpecialParse gson) {
    return new CustomConverterFactory(gson);
  }
  
  private final SpecialParse gson;
  
  private CustomConverterFactory(SpecialParse gson) {
    if (gson == null) {
      throw new NullPointerException("gson == null");
    }
    this.gson = gson;
  }
  
  private boolean isConverter(Type type){
    if(type instanceof Class){
      Class clazz= (Class) type;
      Type[] genericInterfaces = clazz.getGenericInterfaces();
      for (Type anInterface : genericInterfaces) {
        if(IKey.class.isAssignableFrom((Class) anInterface)){
          System.out.println("IKey 类型。。。。。");
          return true;
        }
      }
    }
    return false;
  }
  
  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    boolean isConverter=false;
    if(type instanceof ParameterizedType){
      Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments();
      for (Type argument : typeArguments) {
        isConverter=isConverter(argument);
      }
    }else{
      isConverter=isConverter(type);
    }
    if(isConverter){
      // 使用自定义的内容解析器
      return new CustomResponseBodyConverter<>(type,gson);
    }
    return super.responseBodyConverter(type, annotations, retrofit);
  }
  
  @Override
  public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    System.out.println("requestBodyConverter"+type);
   
    return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
  }
  
  @Override
  public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    
    return super.stringConverter(type, annotations, retrofit);
  }
}

